<template>
  <div>
    <el-dialog v-model="visible" :title="vpcID ? '编辑' : '新建'" class="add-vpc-dialog">
      <el-form
        ref="formRef"
        :model="form"
        :rules="vpcRules"
        class="m-auto mt-1"
      >
        <el-form-item label="VPC名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="计算节点" prop="computerID" v-if="!vpcID">
          <el-select
              filterable
              clearable
              v-model="form.computerID"
              style="width: 100%"
          >
            <el-option-group
                v-for="nets in networkList"
                :key="nets.ID"
                :label="nets.name"
            >
              <el-option
                  v-for="net in nets.computers"
                  :key="net.ID"
                  :label="net.name"
                  :value="net.ID"
                  :disabled="!net.status"
              />
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="端口数量" prop="portNumber" v-if="!vpcID">
          <el-input-number v-model.number="form.portNumber" min="1" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input type="textarea" :rows="6" v-model="form.desc" min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="addOrEditVMData" :loading="loading"> {{ vpcID ? '保 存' : '新 建'}} </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {onUnmounted, reactive, ref, shallowReactive, shallowRef, watch} from 'vue';
import { emitter } from '@/utils/bus';
import { getCluster } from '@/api/topo/simulationApi/cluster';
import { ElMessage } from 'element-plus';
import {addVPCApi, editVPCApi} from "@/api/topo/simulationApi/vpc";
import {setObjectValue} from "@/utils/common";
import { useOperateStatus } from '@/pinia/modules/operateStatus';
let useOperate = useOperateStatus();

const visible = ref(false);
const formRef = ref(null);
const component = ref(null);
const image = ref(null);
const networkList = ref([]);
const loading = ref(false);
const form = reactive({
  name: '',
  desc: '',
  portNumber: null,
  computerID: null
});
const emit = defineEmits(['updateData']);

// vpc表单校验规则
let vpcRules = {
  name: [{ required: true, message: 'vpc名称不能为空', trigger: 'blur' }],
  computerID: [
    { required: true, message: '请选择计算节点', trigger: 'change' },
  ],
  portNumber: [{ required: true, message: '端口数量不能为空', trigger: 'blur' }],
};

let vpcID = ref('');

/**
 * 新建、编辑虚拟机（控制弹窗显示/隐藏）
 */
const addOrEditVPCFunc = (data) => {
  visible.value = true;
  vpcID.value = data ? data.ID : '';

  if(data) {
    setObjectValue(form, data);
  }
  form.portNumber = data?.ports?.length ? data?.ports?.length : null;
};
emitter.on('addOrEditVPC_bus', addOrEditVPCFunc);

/**
 * 确认添加VPC
 */
const addOrEditVMData = () => {
  formRef.value?.validate(async valid => {
    if (valid) {

      loading.value = true;
      if(vpcID.value) {
        editVPCApi(vpcID.value, form).then(res => {
          if (!(res instanceof Error)) {
            ElMessage.success('编辑成功');
            visible.value = false;
            loading.value = false;
            emitter.emit('vpcUpdateData');
            emitter.emit('vpc_update_task', { computerId: form.computerID, node: res.data });
          } else {
            loading.value = false;
          }
        }).catch(err =>{
          loading.value = false;
        })
      } else {
        addVPCApi(form).then(res => {
          if (!(res instanceof Error)) {
            ElMessage.success('新建成功');
            visible.value = false;
            loading.value = false;
            useOperate.setOperateStatus('vpc', { id: res.data.taskID, type: 'add' });
          } else {
            loading.value = false;
          }
        }).catch(err =>{
          loading.value = false;
        })
      }
    }
  });
};

// 获取网络列表
const getNetworkArr = async () => {
  const res = await getCluster({ pageSize: 9999, page: 1 });
  networkList.value = res.data.list;
};

// 监听弹窗显示、隐藏（隐藏重置表单、显示调用接口）
watch(
    visible,
    () => {
      if (!visible.value) {
        formRef.value?.resetFields();
        component.value = null;
      } else {
        getNetworkArr();
      }
    },
    { immediate: false },
);

/**
 * 卸载-生命周期（主要处理清除定时器、解绑操作）
 */
onUnmounted(() => {
  emitter.off('addOrEditVPC_bus', addOrEditVPCFunc);
});
</script>
<style lang="scss" scoped>
:deep(.add-vpc-dialog) {
  width: 560px;
  .el-form {
    max-width: 460px;
    .el-form-item__label {
      width: 100px;
    }
  }
}
</style>
